// pages/order/activitySure/activitySure.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        couponShow: false,
        goodsId: 0,
        goodsNum: 1,
        cartIds: '',

        // 订单数据
        address: null,
        coupon_list: [],
        delivery: "10",
        deliverySetting: ["10", "20"],
        exist_address: false,
        express_price: "0.00",
        extract_shop: [],
        goods_list: [],
        intra_region: true,
        order_pay_price: "0.00",
        order_total_num: "1",
        order_total_price: "0.00",
        goods_total_price: "0.00",
        point_total_price: "0.00",
        coupon_total_price: "0.00",
        user_points: "0",
        pay_type: 20,
        points_setting: null,
        point: {
            subtract_goodsTotalPrice: "0.00",
            usage_quantity: "0"
        },
        remark: '',

        // 是否开启积分兑换
        is_point_exchange: 0,
        // 是否选择优惠券
        chooseCoupon: null,
        // 门店列表
        shopList: [],
        chooseShop: null,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.data.goodsId = options.id;
        this.loadGoodsDetail();
    },

    // 选择优惠券
    chooseCouponChange: function(e) {
        this.groupSetData(() => {
            const chooseCoupon = e.detail;
            this.setData({
                chooseCoupon: chooseCoupon,
            });
            this.updateTotalAmount();
        });
    },

    // 加载商品详情
    loadGoodsDetail: function() {
        return wx.http.get('api/activity/buyNow', {
            goods_id: this.data.goodsId,
            goods_num: this.data.goodsNum,
            point: 1,
        }).then((res) => {
            this.groupSetData(() => {
                this.setData(res.data.data);
                this.updateTotalAmount();
            });
            return res.data.data;
        }, (err) => {
            console.warn("api/activity/buyNow", err)
        });
    },

    // 修改商品数量
    modifyGoodsNumTap: function(e) {
        const dataset = e.currentTarget.dataset,
            type = dataset.type;

        let totalNum = this.data.goodsNum;

        // 减少
        if (type === '0') {
            totalNum = totalNum > 1 ? totalNum - 1 : 1;
        } else { // 增加
            totalNum++;
        }

        this.groupSetData(() => {
            const totalPrice = new wx.BigNumber(this.data.goods_list.activity_money).multipliedBy(totalNum).toFixed(2, wx.BigNumber.ROUND_DOWN);
            this.setData({
                goodsNum: totalNum,
                'goods_list.total_price': totalPrice,
            });
            this.updateTotalAmount();

            // 更新coupon
            this.updateCoupon(totalNum);
        });
    },

    // 重新计算总价格
    updateTotalAmount: function() {
        // 商品金额
        let goodsTotalPrice = new wx.BigNumber('0.00');
        goodsTotalPrice = goodsTotalPrice.plus(this.data.goods_list.total_price)

        // 订单总金额
        let orderTotalPrice = goodsTotalPrice.plus('0.00');
        if (parseInt(this.data.delivery) === 10) {
            orderTotalPrice = orderTotalPrice.plus(this.data.express_price);
        }

        // 优惠券折扣金额
        let couponTotalPrice = new wx.BigNumber('0.00');
        let chooseCoupon = this.data.chooseCoupon;
        if (chooseCoupon) {
            // 如果是折扣券
            if (chooseCoupon.coupon_type.value === 20) {
                couponTotalPrice = new wx.BigNumber(10);
                couponTotalPrice = couponTotalPrice.minus(chooseCoupon.discount).div(10).multipliedBy(orderTotalPrice);
            } else {
                couponTotalPrice = new wx.BigNumber(chooseCoupon.reduce_price);
            }
        }

        // 积分折扣金额
        let pointTotalPrice = new wx.BigNumber('0.00');
        if (this.data.is_point_exchange) {
            // const pointSetting = this.data.points_setting;
            // pointTotalPrice.plus(this.data.user_points).times(pointSetting)
            pointTotalPrice = new wx.BigNumber(this.data.point.subtract_goodsTotalPrice);
        }

        // 实际支付金额
        let orderPayPrice = orderTotalPrice.minus(pointTotalPrice).minus(couponTotalPrice);

        this.setData({
            goods_total_price: goodsTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
            order_total_price: orderTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
            order_pay_price: orderPayPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
            point_total_price: pointTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
            coupon_total_price: couponTotalPrice.toFixed(2, wx.BigNumber.ROUND_DOWN),
        });
    },

    // 是否开启积分兑换
    pointExchangeChange: function(e) {
        this.data.is_point_exchange = e.detail.value ? 1 : 0;
        this.updateTotalAmount();
    },

    // 跳转订单列表
    goOrder: function() {
        wx.redirectTo({
            url: '/pages/activity/detail/detail?id=' + this.data.goodsId
        })
    },

    // 立即购买
    payTap: function(e) {
        const values = e.detail.value;
        const chooseCoupon = this.data.chooseCoupon;
        const chooseShop = this.data.chooseShop;
        const address = this.data.address;
        wx.http.post('api/activity/buyNow', {
            name: values.name,
            phone: values.phone,
            people_num: values.people,
            remark: values.remark,
            goods_id: this.data.goodsId,
            goods_num: this.data.goodsNum,
            point: this.data.is_point_exchange ? this.data.point.usage_quantity : 0,
            coupon_id: chooseCoupon ? chooseCoupon.user_coupon_id : 0,
        }).then((res) => {
            const payInfo = res.data.data.payment;

            wx.promise.requestPayment({
                timeStamp: payInfo.timeStamp,
                nonceStr: payInfo.nonceStr,
                package: 'prepay_id=' + payInfo.prepay_id,
                signType: 'MD5',
                paySign: payInfo.paySign,
            }).then(() => {
                this.goOrder();
            }, () => {
                wx.showToast({
                    title: '支付失败',
                    icon: 'none',
                });
            });
        });
    },



    // 更新优惠券
    updateCoupon: function (goodsNum) {
        if (goodsNum === this.data.goodsNum) return;
        console.log('update coupon ...')

        return wx.http.get('api/activity/buyNow', {
            goods_id: this.data.goodsId,
            goods_num: this.data.goodsNum,
            point: 1,
        }).then((res) => {
            const data = res.data.data;
            const couponList = data.coupon_list;

            let chooseCoupon = this.data.chooseCoupon;
            if (couponList.length && chooseCoupon) {
                const index = couponList.findIndex(cp => {
                    return chooseCoupon.user_coupon_id === cp.user_coupon_id;
                });
                if (index === -1) chooseCoupon = null;
            } else {
                chooseCoupon = null;
            }

            this.groupSetData(() => {
                if (chooseCoupon === null && this.data.chooseCoupon !== null) {
                    this.data.chooseCoupon = null;
                    console.log('sszzz');
                    this.updateTotalAmount();
                }

                this.setData({
                    coupon_list: couponList,
                    chooseCoupon: chooseCoupon
                });
            });

            return res.data.data;
        }, (err) => {
            console.warn("api/goods/detail", err)
        });
    },

})